package com.syj.collect.fragment;


import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.syj.collect.adapter.AdapterProjectList;
import com.syj.collect.app.R;
import com.syj.collect.base.BaseFragment;
import com.syj.collect.base.EmptyRecyclerView;
import com.syj.collect.entry.StatisticsInfoBean;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.entry.UserTaskListBean;
import com.syj.collect.http.BaseObserver;
import com.syj.collect.http.BaseRequest;
import com.syj.collect.utils.DataUtils;
import com.syj.collect.utils.GsonUtil;
import com.syj.collect.utils.SPUtil;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class NewsFragment extends BaseFragment implements View.OnClickListener {

    private EmptyRecyclerView rec;

    private boolean changeState ;
    private String[] menu = {"已采集", "未采集", "审核未通过", "已提交", "未提交", "新任务"};
    private TextView title;

    private SmartRefreshLayout refresh;
    @Override
    protected int getLayoutId() {
        return R.layout.fargment_news;
    }
    private  TextView tv_iscollect;
    private  TextView tv_uncollect;
    private  TextView tv_unaudit;
    private  TextView tv_issubmit;
    private  TextView tv_unsubmit;
    private  TextView tv_newtask;
    private  int  type;
    private  TextView f_news_list_num;
    private ImageView iv;
    private int cruntPage = 1;//第一页
    private  int pagetype=1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        rec = (EmptyRecyclerView) rootView.findViewById(R.id.com_rerec);
        refresh = rootView.findViewById(R.id.comm_refresh);
        rec.setEmptyView(rootView.findViewById(R.id.empty_view_));
        rootView.findViewById(R.id.f_news_li1).setOnClickListener(this);
        rootView.findViewById(R.id.f_news_li2).setOnClickListener(this);
        rootView.findViewById(R.id.f_news_li3).setOnClickListener(this);
        rootView.findViewById(R.id.f_news_li4).setOnClickListener(this);
        rootView.findViewById(R.id.f_news_li5).setOnClickListener(this);
        rootView.findViewById(R.id.f_news_li6).setOnClickListener(this);
        title = (TextView) rootView.findViewById(R.id.f_news_list_title);
        iv = (ImageView) rootView.findViewById(R.id.change);

        tv_iscollect = (TextView) rootView.findViewById(R.id.tv_iscollect);
        tv_uncollect = (TextView) rootView.findViewById(R.id.tv_uncollect);
        tv_unaudit = (TextView) rootView.findViewById(R.id.tv_unaudit);
        tv_issubmit = (TextView) rootView.findViewById(R.id.tv_issubmit);
        tv_unsubmit = (TextView) rootView.findViewById(R.id.tv_unsubmit);
        tv_newtask = (TextView) rootView.findViewById(R.id.tv_newtask);

        f_news_list_num = (TextView) rootView.findViewById(R.id.f_news_list_num);

        title.setText(menu[0]);
        rootView.findViewById(R.id.change).setOnClickListener(this);
        adapterProjectLis = new AdapterProjectList(changeState ? 0 : 1, getActivity());

        rec.setLayoutManager(changeState ? new LinearLayoutManager(rec.getContext()) : new GridLayoutManager(rec.getContext(), 3));
        rec.setAdapter(adapterProjectLis);
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                switch (pagetype){
                    case 1:
                        initData(3,"","",++cruntPage);//已经采集
                        break;
                    case 2:
                        initData(1,"","",++cruntPage);//未采集
                        break;
                    case 3:
                        getTaskList(3,0,++cruntPage);//审核未通过
                        break;
                    case 4:
                        getTaskList(0,1,++cruntPage);//已提交
                        break;
                    case 5:
                        getTaskList(0,0,++cruntPage);//未提交
                        break;
                    case 6:
                        initData(1,DataUtils.GetDateone(),DataUtils.getPastDate(3),++cruntPage);//新任务
                        break;
                }
//                present.getAll(++cruntPage);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                cruntPage = 1;
                switch (pagetype){
                    case 1:
                        initData(3,"","",cruntPage);//已经采集
                        break;
                    case 2:
                        initData(1,"","",cruntPage);//未采集
                        break;
                    case 3:
                        getTaskList(3,0,cruntPage);//审核未通过
                        break;
                    case 4:
                        getTaskList(0,1,cruntPage);//已提交
                        break;
                    case 5:
                        getTaskList(0,0,cruntPage);//未提交
                        break;
                    case 6:
                        initData(1,DataUtils.GetDateone(),DataUtils.getPastDate(3),cruntPage);//新任务
                        break;
                }


            }
        });

        inittitle();//加载上面的数据
        initData(3,"","",cruntPage);//加载下面的数据

        return rootView;
    }

    @Override
    protected void onVisible() {
        super.onVisible();
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden){
            inittitle();
            initData(3,"","",cruntPage);//加载下面的数据
        }
    }
    private StatisticsInfoBean statisticsInfoBean;
    public  void  inittitle(){
        String userstr = SPUtil.getPrefString("userInfo", "");
        Gson gson = new Gson();
        UserInfoBean.UserInfo userInfo = gson.fromJson(userstr, UserInfoBean.UserInfo.class);
        int userid=userInfo.getUserId();
        HashMap hashMap = new HashMap();
        hashMap.put("userId", userid);//不写为所有用户
        String str = gson.toJson(hashMap);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        BaseRequest.getInstance().getApiServise().getStatisticsInfo(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        statisticsInfoBean = GsonUtil.gsonToBean(value, StatisticsInfoBean.class);
                        tv_iscollect.setText(statisticsInfoBean.getData().getIsCollect()+"");
                        tv_uncollect.setText(statisticsInfoBean.getData().getUnCollect()+"");
                        tv_unaudit.setText(statisticsInfoBean.getData().getUnAudit()+"");
                        tv_issubmit.setText(statisticsInfoBean.getData().getIsSubmit()+"");
                        tv_unsubmit.setText(statisticsInfoBean.getData().getUnSubmit()+"");
                        tv_newtask.setText(statisticsInfoBean.getData().getNewTask()+"");
                        f_news_list_num.setText(statisticsInfoBean.getData().getIsCollect()+"");
                        return false;
                    }
                    @Override
                    public void onFailure(Throwable e) throws Exception {

                    }
                    @Override
                    public void onEnd() {
                    }
                });
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.change:
                changeState = !changeState;
                    if (changeState){
                        initstart();
                    }else {
                        initleftstart();
                    }

                break;
            case R.id.f_news_li1:
                title.setText(menu[0]);
                f_news_list_num.setText(statisticsInfoBean.getData().getIsCollect()+"条");
                pagetype=1;
                cruntPage=1;
                initData(3,"","",cruntPage);//已经采集
                // 需要跳转到任务详情
                break;
            case R.id.f_news_li2:
                title.setText(menu[1]);
                f_news_list_num.setText(statisticsInfoBean.getData().getUnCollect()+"");
                pagetype=2;
                cruntPage=1;
                initData(1,"","",cruntPage);//未采集
                // 需要跳转到任务详情
                break;
            case R.id.f_news_li3:
                title.setText(menu[2]);
                f_news_list_num.setText(statisticsInfoBean.getData().getUnAudit()+"");
                pagetype=3;
                cruntPage=1;
                inittitle();//加载上面的数据
                getTaskList(3,0,cruntPage);//审核未通过
                break;
            case R.id.f_news_li4:
                title.setText(menu[3]);
                f_news_list_num.setText(statisticsInfoBean.getData().getIsSubmit()+"");
                pagetype=4;
                cruntPage=1;
                getTaskList(0,1,cruntPage);//已提交
                break;
            case R.id.f_news_li5:
                title.setText(menu[4]);
                f_news_list_num.setText(statisticsInfoBean.getData().getUnSubmit()+"");
                pagetype=5;
                cruntPage=1;
                inittitle();//加载上面的数据
                getTaskList(0,0,cruntPage);//未提交
                //加载任务页面， 需要跳转到任务详情
                break;
            case R.id.f_news_li6:
                title.setText(menu[5]);
                f_news_list_num.setText(statisticsInfoBean.getData().getNewTask()+"");
                pagetype=6;
                cruntPage=1;
                inittitle();//加载上面的数据
                initData(1,DataUtils.GetDateone(),DataUtils.getPastDate(3),cruntPage);//新任务
                break;

        }
        setChange();
    }

    private void initstart() {
        Animation rotateAnimation = new RotateAnimation(0f, 90, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setDuration(0);
        rotateAnimation.setRepeatCount(0);
        rotateAnimation.setRepeatMode(Animation.REVERSE);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setDetachWallpaper(true);
        iv.startAnimation(rotateAnimation);

    }


    private void initleftstart() {
        Animation rotateAnimation = new RotateAnimation(0f, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setDuration(0);
        rotateAnimation.setRepeatCount(0);
        rotateAnimation.setRepeatMode(Animation.REVERSE);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setDetachWallpaper(true);
        iv.startAnimation(rotateAnimation);

    }

    public void getTaskList(int audiStatus,int isSubmit,int page) {
        HashMap hashMap = new HashMap();
        //hashMap.put("isCollect", "1");//可选
        String value = SPUtil.getPrefString("userInfo", "");
        Gson gson = new Gson();
        UserInfoBean.UserInfo gBean = gson.fromJson(value, UserInfoBean.UserInfo.class);
        hashMap.put("userId", gBean.getUserId());//不写为所有用户
        hashMap.put("auditStatus", String.valueOf(audiStatus));//审核状态  0 这里不用未审核 2 审核通过 3审核未通过    auditStatus
        hashMap.put("isSubmit",String.valueOf(isSubmit));
        hashMap.put("page", page + "");
        if (audiStatus==0){
            hashMap.remove("auditStatus");
        }
        if (audiStatus==3){
            hashMap.remove("isSubmit");
        }


        String str = gson.toJson(hashMap);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        // Log.e("1", str);

        BaseRequest.getInstance().getApiServise().getUserCollectList(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        if(refresh!=null)refresh.finishLoadMore();
                        if(refresh!=null)refresh.finishRefresh();
//                        Log.e("task1结果?", value);
                        UserTaskListBean userTaskListBean = GsonUtil.gsonToBean(value, UserTaskListBean.class);
                        cruntPage=userTaskListBean.getData().getCurrPage();
                        taskListBeanData = userTaskListBean.getData().getList();
                        if (cruntPage==1){
                            gridtBeanData=taskListBeanData;
                        }else {
                            gridtBeanData.addAll(taskListBeanData);
                        }
                        //区分跳转
                        if (audiStatus==3){
                            //审核未通过，
                            type=3;

                            if (cruntPage==1){

                                adapterProjectLis.upData(taskListBeanData,3);
                            }else {
                                adapterProjectLis.AddData(taskListBeanData,3);
                            }

                        }else if (audiStatus==0&&isSubmit==1){
                            //已经提交
                            type=4;
                            if (cruntPage==1){
                                adapterProjectLis.upData(taskListBeanData,4);
                            }else {
                                adapterProjectLis.AddData(taskListBeanData,4);
                            }

                        }else {
                            //未提交
                            type=5;
                            if (cruntPage==1){
                                adapterProjectLis.upData(taskListBeanData,5);
                            }else {
                                adapterProjectLis.AddData(taskListBeanData,5);
                            }
                        }

                        return false;
                    }
                    @Override
                    public void onFailure(Throwable e) throws Exception {
//                        view.initFail("网络异常");
                    }
                    @Override
                    public void onEnd() {

                    }
                });
    }
    //    private String[] menu = {"已采集", "未采集", "审核未通过", "已提交", "未提交", "新任务"};
    private  List<UserTaskListBean.DataDTO.ListDTO> taskListBeanData;
    private  List<UserTaskListBean.DataDTO.ListDTO> gridtBeanData;//给另外一个adapt而用
    public  void  initData(int status,String endTime,String startTime,int page){
        HashMap hashMap = new HashMap();
        String value = SPUtil.getPrefString("userInfo", "");
        Gson gson = new Gson();
        UserInfoBean.UserInfo gBean = gson.fromJson(value, UserInfoBean.UserInfo.class);
        hashMap.put("userId", gBean.getUserId());//不写为所有用户
        hashMap.put("status", String.valueOf(status));
        hashMap.put("endTime", endTime);
        hashMap.put("startTime", startTime);
        hashMap.put("page", page + "");
        if (endTime.isEmpty()){
            hashMap.remove("endTime");
        }
        if (startTime.isEmpty()){
            hashMap.remove("startTime");
        }
        String str = gson.toJson(hashMap);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        // Log.e("1", str);

        BaseRequest.getInstance().getApiServise().getUserTasklist(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        if(refresh!=null)refresh.finishLoadMore();
                        if(refresh!=null)refresh.finishRefresh();
                        UserTaskListBean userTaskListBean = GsonUtil.gsonToBean(value, UserTaskListBean.class);
                        cruntPage=userTaskListBean.getData().getCurrPage();
                         taskListBeanData = userTaskListBean.getData().getList();
                        if (cruntPage==1){
                            gridtBeanData=taskListBeanData;
                        }else {
                            gridtBeanData.addAll(taskListBeanData);
                        }
                        if (status==1){
                            //新任务
                            type=6;
                            if (cruntPage==1){
                                adapterProjectLis.upData(taskListBeanData,6);
                            }else {
                                adapterProjectLis.AddData(taskListBeanData,6);
                            }
                        }else if (status==3){
                            //已经采集
                            type=1;
                            if (cruntPage==1){
                                adapterProjectLis.upData(taskListBeanData,1);
                            }else {
                                adapterProjectLis.AddData(taskListBeanData,1);
                            }
                        }else {
                            //未采集
                            type=2;
                            if (cruntPage==1){
                                adapterProjectLis.upData(taskListBeanData,2);
                            }else {
                                adapterProjectLis.AddData(taskListBeanData,2);
                            }
                        }

                        return false;
                    }
                    @Override
                    public void onFailure(Throwable e) throws Exception {
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }
    private   AdapterProjectList adapterProjectLis;
    private void setChange() {
        adapterProjectLis = new AdapterProjectList(changeState ? 0 : 1,getActivity());
        rec.setLayoutManager(changeState ? new LinearLayoutManager(rec.getContext()) : new GridLayoutManager(rec.getContext(), 3));
        rec.setAdapter(adapterProjectLis);

//        adapterProjectLis.updataType(1);
        if (cruntPage==1){
            adapterProjectLis.upData(gridtBeanData,type);
        }else {
            adapterProjectLis.AddData(gridtBeanData,type);
        }


//        adapterProjectLis.upData(taskListBeanData, type);


    }

    private void initColoct(int pos) {
//        taskListBeanData.get(pos).
        HashMap hashMap = new HashMap();
        String value = SPUtil.getPrefString("userInfo", "");
        Gson gson = new Gson();
        UserInfoBean.UserInfo gBean = gson.fromJson(value, UserInfoBean.UserInfo.class);
        hashMap.put("userId", gBean.getUserId());//不写为所有用户
        hashMap.put("isCollect", "0");//不写为所有用户


        String str = gson.toJson(hashMap);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        BaseRequest.getInstance().getApiServise().getUserCollectList(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("task1结果?", value);

                        return false;
                    }
                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        //view.initFail("网络异常");
                    }
                    @Override
                    public void onEnd() {

                    }
                });
    }
}
